#include "databaseconn.h"
#include <QDir>
#include <QApplication>
#include <QSqlQuery>


DatabaseConn::DatabaseConn(QObject* parent) : QObject(parent)
{
    databaseName = QApplication::applicationDirPath();
    databaseName.append(QDir::separator()).append("icarus.db");
    qDebug(databaseName.toLatin1());
}


bool DatabaseConn::openDB()
{
    // Find QSLite driver
    db = QSqlDatabase::addDatabase("QSQLITE");

    #ifdef Q_OS_LINUX
    // NOTE: We have to store database file into user home folder in Linux
    /*QString path(QApplication::applicationDirPath());
    path.append(QDir::separator()).append("my.db.sqlite");
    path = QDir::toNativeSeparators(path);
    qDebug(path.toLatin1());*/
    db.setDatabaseName(databaseName);
    #else
    // NOTE: File exists in the application private folder, in Symbian Qt implementation
    db.setDatabaseName("my.db.sqlite");
    #endif

    // Open databasee
    return db.open();
}

QSqlError DatabaseConn::lastError()
{
    // If opening database has failed user can ask
    // error description by QSqlError::text()
    return db.lastError();
}

bool DatabaseConn::closeConnection(){
   db.close();
   return true;
}

bool DatabaseConn::openConnection(){

    qDebug("opening connection");

    db = QSqlDatabase::addDatabase("QSQLITE");

    db.setDatabaseName(databaseName);
    bool ok = db.open();
    qDebug("%d",db.tables().size());

    QSqlQuery query;
    query.exec("select * from clients");

    qDebug("size:%d",query.size());
    qDebug("query.isselect=%d",query.isSelect());
    qDebug("isValid=%d",query.isValid());


    return ok;
}

DatabaseConn::~DatabaseConn(){

}
